package com.amcase.demk.base;

import com.alibaba.druid.support.json.JSONUtils;
import com.amcase.demk.model.User;
import lombok.extern.java.Log;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName:BaseController
 * @Decription:TODO
 * @Author:amcase
 * @Data:2018/4/11 15:32
 * @Version:1.0
 **/
@Log
public class BaseController {
    private HttpServletRequest request;
    private HttpServletResponse response;
    private User user;
    private HttpSession session;

    protected Map<String,Object> getPara(){
        Map<String,Object> param = new HashMap<>();
        String method = request.getMethod();
        Enumeration<?> keys = request.getParameterNames();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            if (key != null) {
                if (key instanceof String) {
                    String value = request.getParameter(key.toString());
                    if ("GET".equals(method)) {//前台encodeURIComponent('我们');转码后到后台还是ISO-8859-1，所以还需要转码
                        try {
                            value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    param.put(key.toString(), value);
                }
            }
        }
        return param;
    }
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
        this.request = request;
        this.response = response;
        this.session = request.getSession();
        this.user=(User) this.session.getAttribute("userMessage");
    }
    protected  HttpSession getSession(HttpServletRequest request){
        HttpSession session =request.getSession();
        return session;
    }
    protected void rendToJson(Map<String,Object> map) throws IOException {
        String jo = JSONUtils.toJSONString(map);
        PrintWriter pw = response.getWriter();
        pw.write(jo);
    }
}
